package com.neusoft.neuiotms.dcom.converter.hn;

import java.util.ArrayList;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.google.common.collect.Lists;
import com.neusoft.bizcore.web.dto.AbstractConverter;
import com.neusoft.neuiotms.dcom.dto.hn.HnInspectionItemDTO;
import com.neusoft.neuiotms.dcom.model.hn.HnInspectionItem;
import com.neusoft.neuiotms.dcom.repository.hn.HnInspectionItemRepository;

@Component
public class HnInspectionItemConverter extends AbstractConverter<HnInspectionItem, HnInspectionItemDTO> {

    @Autowired
    private HnInspectionItemRepository hnInspectionItemRepository;

    @Override
    public HnInspectionItem toModel(final HnInspectionItemDTO dto) {
        HnInspectionItem model;
        if (dto.isNew()) {
            model = new HnInspectionItem();
        } else {
            model = this.hnInspectionItemRepository.getOne(dto.getId());
        }
        model.setCandidateValue(dto.getCandidateValue());
        model.setCategory(dto.getCategory());
        model.setDataType(dto.getDataType());
        model.setDisabled(dto.isDisabled());
        model.setItem(dto.getItem());
        model.setItemType(dto.getItemType());
        model.setUpdateTime(dto.getUpdateTime());
        model.setRule(dto.getRule());
        model.setUnit(dto.getUnit());
        model.setUserCode(dto.getUserCode());
        model.setUserName(dto.getUserName());
        if (!dto.getCandidateValueArr().isEmpty()) {
            final StringBuffer sBuffer = new StringBuffer();
            dto.getCandidateValueArr().forEach(t -> {
                sBuffer.append(t.trim()).append(",");
            });
            model.setCandidateValue(sBuffer.toString());
        }
        model.setSort(dto.getSort());
        return model;
    }

    @Override
    public HnInspectionItemDTO toDTO(final HnInspectionItem model, final boolean forListView) {
        final HnInspectionItemDTO dto = new HnInspectionItemDTO();
        dto.setCandidateValue(model.getCandidateValue());
        dto.setCategory(model.getCategory());
        dto.setCreateTime(model.getCreateTime());
        dto.setDataType(model.getDataType());
        dto.setId(model.getId());
        dto.setDisabled(model.isDisabled());
        dto.setItem(model.getItem());
        dto.setItemType(model.getItemType());
        dto.setRule(model.getRule());
        dto.setUnit(model.getUnit());
        dto.setUpdateTime(model.getUpdateTime());
        dto.setUserCode(model.getUserCode());
        dto.setUserName(model.getUserName());
        if (StringUtils.isNotBlank(model.getCandidateValue())) {
            final ArrayList<String> arr = Lists.newArrayList(model.getCandidateValue().split(","));
            dto.setCandidateValueArr(arr);
            dto.setCandidateValue(model.getCandidateValue());
        }
        dto.setSort(model.getSort());
        return dto;
    }

}
